#
# openlookup/lib/stateless.py
#
# Copyright 2009 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

"""
Wrap a class so that each method operates on a new instance.

The class must implement the context protocol.
"""

from __future__ import with_statement

class Stateless(object):
    def __init__(self, factory, *args, **kwargs):
        self.factory = factory
        self.args = args
        self.kwargs = kwargs

    def __getattr__(self, name):
        function = getattr(self.factory, name)

        def proxy(*args, **kwargs):
            with self.factory(*self.args, **self.kwargs) as instance:
                return function(instance, *args, **kwargs)

        return proxy

class Test(object):
    """
    Quick test

    >>> with Test(1, b=2) as handle:
    ...   result = handle.test(3, d=4)
    Enter
    Test: (1, 2, 3, 4)
    Exit
    >>> result
    'OK'

    >>> handle = Stateless(Test, 1, b=2)
    >>> result = handle.test(3, d=4)
    Enter
    Test: (1, 2, 3, 4)
    Exit
    >>> result
    'OK'
    >>>
    """
    def __init__(self, a, b=None):
        self.a = a
        self.b = b

    def __enter__(self):
        print 'Enter'
        return self

    def __exit__(self, *exc_info):
        print 'Exit'

    def test(self, c, d=None):
        print 'Test:', (self.a, self.b, c, d)
        return 'OK'

if __name__ == '__main__':
    import doctest
    doctest.testmod()
